﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Filldata();
            }
        }
        private void Filldata()
        {
            var sql =" select * from Articles ";
            var dt = DbHelper.GetDataTable(sql);
            gv1.DataSource = dt;
            gv1.DataBind();

        }

        protected void gv1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetValue(e.RowIndex, 0);
            var sql = string.Format("delete from Articles where id='{0}'", id);
            DbHelper.AddOrUpdateOrDelete(sql);
            gv1.EditIndex = -1;
            Filldata();

        }

        protected void gv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var id = GetValue(e.RowIndex, 0).Replace("&nbsp;", "");
            var Title = GetValue(e.RowIndex, 1);
            var Content = GetValue(e.RowIndex, 2);
            var Author = GetValue(e.RowIndex, 3);
            if (string.IsNullOrEmpty(id))
            {
                 var sql = string.Format("insert into Articles(Title,Content,Author)values('{0}','{1}','{2}')",Title,Content,Author);
                DbHelper.AddOrUpdateOrDelete(sql);

            }
            else
            {
                var sql = string.Format("update Articles set Title='{0}',Content='{1}',Author='{2}' where id='{3}'",Title,Content,Author,id);
                DbHelper.AddOrUpdateOrDelete(sql);
            }
            gv1.EditIndex = -1;
            Filldata();

        }

        private string GetValue(int rowIndex, int colIndex)
        {
            var cont = gv1.Rows[rowIndex].Cells[colIndex];
            var value = cont.Controls.Count > 0 ? ((TextBox)cont.Controls[0]).Text : cont.Text;
            return value;
        
        
        
        }

        protected void gv1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gv1.EditIndex = e.NewEditIndex;
            Filldata();

        }

        protected void gv1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gv1.EditIndex = -1;
            Filldata();
        }

        
    }
}